//
//  HLiveSendGiftView.m
//  linktuIOS
//
//  Created by hejunsong on 2017/1/15.
//  Copyright © 2017年 tianxie. All rights reserved.
//

#import "HLiveSendGiftView.h"
#import "Masonry.h"
#import "GiftCell.h"
#import "giftModel.h"
#import "HMessageTool.h"
#import "MTLiveInputPasswordView.h"
#import "MTLiveApiManager.h"
#import "MTWalletViewController.h"
#import "MTWebViewController.h"
#import "MTWalletViewController.h"

@interface HLiveSendGiftView()<UICollectionViewDelegate,UICollectionViewDataSource>
@property(nonatomic,strong) UICollectionView *collectView;
@property(nonatomic,strong) UIView *bottomToolView;

@property(nonatomic,strong) UILabel *diamondLabel;
@property(nonatomic,strong) UILabel *diamondNumberLabel;
@property(nonatomic,strong) UIButton *topupButton;

@property(nonatomic,strong) UIButton *sendButton;
@property(nonatomic,strong) UIButton *countdownButton;

@property(nonatomic,strong) NSMutableArray *giftModelArray;

@property(nonatomic,strong) giftModel *selectgiftmodel;

@property(nonatomic,weak) KLCPopup *pop;

@property(nonatomic,strong) UIButton *countDownButton;

@property(nonatomic,assign) NSInteger viewerMoney;

@property(nonatomic,assign) NSInteger receivedCount;

@property(nonatomic,strong) NSTimer *giftCountDownTimer;

@property(nonatomic,strong) NSTimer *giftRefrshTimer;

@property(nonatomic,strong) giftModel *lastGiftModel;

@property(nonatomic,strong) NSMutableArray *sendGiftModelArray;

@property(nonatomic,strong) NSTimer *timer;

@property(nonatomic,strong) UILabel *continueLabel;
@property(nonatomic,strong) UILabel *countTimeLabel;

@property(nonatomic,strong) MTLiveInputPasswordView *passwordView;

@property(nonatomic,copy) NSString *token;

@end

@implementation HLiveSendGiftView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.viewerMoney = 0;
        [self makeUI];
        [self viewerMoneyRefresh];
        self.giftCountDownTimer = [NSTimer scheduledTimerWithTimeInterval:4/40.0 target:self selector:@selector(giftCountDownRefresh) userInfo:nil repeats:YES];
        [self.giftCountDownTimer setFireDate:[NSDate distantFuture]]; //暂停定时器
    }
    return self;
}

+(instancetype)sendGiftView
{
    CGFloat bottomBarH = 0;
    if(iSiPhoneX)
    {
        bottomBarH = 34;
    }
    HLiveSendGiftView *giftView = [[HLiveSendGiftView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, RelativeValue(201) + bottomBarH)];
    return giftView;
}

-(void)makeUI
{
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    _collectView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) collectionViewLayout:layout];
    _collectView.delegate = self;
    _collectView.dataSource = self;
    _collectView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.8];
//    layout.itemSize = CGSizeMake(40, 40);
    layout.scrollDirection = UICollectionViewScrollDirectionVertical ;// UICollectionViewScrollDirectionHorizontal;
    layout.minimumLineSpacing = 0;
    layout.minimumInteritemSpacing = 0;
    
    [_collectView registerNib:[UINib nibWithNibName:@"GiftCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"giftcellid"];
    _collectView.showsHorizontalScrollIndicator = NO;
    _collectView.showsVerticalScrollIndicator = NO;
    
    
    [self addSubview:_collectView];
    
    
    _bottomToolView = [UIView new];
     _bottomToolView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.8];
    
    [self addSubview:_bottomToolView];
    
    CGFloat bottomBarH = 0;
    if(iSiPhoneX)
    {
        bottomBarH = 34;
    }
    [_bottomToolView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.mas_left).offset(0);
        make.right.mas_equalTo(self.mas_right).offset(0);
        make.bottom.mas_equalTo(self.mas_bottom).offset(0);
        make.height.mas_equalTo(35 + bottomBarH);
    }];
    
    _diamondLabel = [UILabel new];
    _diamondNumberLabel = [UILabel new];
    _topupButton = [UIButton new];
    
    _sendButton = [UIButton new];
    [_sendButton addTarget:self action:@selector(SendGiftClick:) forControlEvents:UIControlEventTouchUpInside];
    
   
    _diamondLabel.text = [NSString stringWithFormat:@"%@:", @"MET"];
    _diamondNumberLabel.text = @"0";
    
    _diamondLabel.font = [UIFont systemFontOfSize:12];
    _diamondNumberLabel.font = [UIFont systemFontOfSize:13];
    
    _diamondNumberLabel.textColor = [UIColor whiteColor];
    _diamondLabel.textColor = mainButtonColor;
    
    _sendButton.backgroundColor =  mainButtonColor;
    [_sendButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_sendButton setTitle:NSLTLocalizedString(@"发送", nil) forState:UIControlStateNormal];
    _sendButton.titleLabel.font = [UIFont systemFontOfSize:14];
    
    [_bottomToolView addSubview:_diamondLabel];
    [_bottomToolView addSubview:_diamondNumberLabel];
    [_bottomToolView addSubview:_topupButton];
    [_bottomToolView addSubview:_sendButton];
    [self addSubview:self.countDownButton];
    
    _topupButton.titleLabel.font = [UIFont systemFontOfSize:12];
    [_topupButton setTitle:NSLTLocalizedString(@"充值", nil) forState:UIControlStateNormal];
    [_topupButton addTarget:self action:@selector(topUp) forControlEvents:UIControlEventTouchUpInside];
    
    [_diamondLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(_bottomToolView.mas_left).offset(10);
        make.centerY.mas_equalTo(_sendButton.mas_centerY).offset(0);
        
//        make.top.mas_equalTo(_bottomToolView.mas_top).offset(0);
//        make.bottom.mas_equalTo(_bottomToolView.mas_bottom).offset(0);
    }];
    
    [_diamondNumberLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(_diamondLabel.mas_right).offset(10);
        make.centerY.mas_equalTo(_sendButton.mas_centerY).offset(0);
    }];
    
    [_topupButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(_diamondNumberLabel.mas_right).offset(10);
        make.centerY.mas_equalTo(_sendButton.mas_centerY).offset(0);
//        make.top.mas_equalTo(_bottomToolView.mas_top).offset(0);
//        make.bottom.mas_equalTo(_bottomToolView.mas_bottom).offset(0);
        make.width.mas_equalTo(@40);
    }];
    [_sendButton mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.right.mas_equalTo(_bottomToolView.mas_right).offset(0);
        make.height.mas_equalTo(@35);
        make.top.mas_equalTo(_bottomToolView.mas_top).offset(0);
//        make.bottom.mas_equalTo(_bottomToolView.mas_bottom).offset(0);
        make.width.mas_equalTo(@50);
        
    }];
    

    [_collectView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.mas_left).offset(0);
        make.right.mas_equalTo(self.mas_right).offset(0);
        make.bottom.mas_equalTo(_bottomToolView.mas_top).offset(0);
        make.top.mas_equalTo(self.mas_top).offset(0);
    }];
}

-(MTLiveInputPasswordView *)passwordView
{
    if(_passwordView == nil)
    {
        _passwordView = [MTLiveInputPasswordView liveinputPasswordView];
    }
    return _passwordView;
}

-(UIButton *)countDownButton
{
    if (!_countDownButton) {
        _countDownButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_countDownButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_countDownButton setBackgroundImage:[UIImage imageNamed:@"btn_send_gift_live"] forState:UIControlStateNormal];
        _countDownButton.layer.cornerRadius = 40;
        _countDownButton.clipsToBounds = YES;
        _countDownButton.frame = CGRectMake(self.width - 85, self.height - 85, 80, 80);
        
        [_countDownButton addTarget:self action:@selector(sendGiftButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
        [self insertSubview:_countDownButton atIndex:self.subviews.count - 1];
        
        
        self.continueLabel = [[UILabel alloc]init];
        self.continueLabel.text = NSLTLocalizedString(@"连送", nil);
        self.continueLabel.textAlignment = NSTextAlignmentCenter;
        self.continueLabel.textColor = [UIColor whiteColor];
        self.continueLabel.font = [UIFont systemFontOfSize:18];
        self.continueLabel.frame = CGRectMake(0, 0, 50, 25);
        self.continueLabel.center = CGPointMake(40, 28);
        [_countDownButton addSubview:self.continueLabel];
        
        
        self.countTimeLabel = [[UILabel alloc]init];
        self.countTimeLabel.textAlignment = NSTextAlignmentCenter;
        self.countTimeLabel.textColor = [UIColor whiteColor];
        self.countTimeLabel.frame = CGRectMake(0, 0, 30, 20);
        self.countTimeLabel.center = CGPointMake(40, 50);
        [_countDownButton addSubview:self.countTimeLabel];
        _countDownButton.hidden = YES;
        
    }
    return _countDownButton;
}
-(void)setGiftViewModel:(HGiftViewModel *)giftViewModel
{
    _giftViewModel = giftViewModel;
    
    

}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.giftViewModel.giftArray.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    GiftCell *cell =  [_collectView dequeueReusableCellWithReuseIdentifier:@"giftcellid" forIndexPath:indexPath];
    cell.model = self.giftViewModel.giftArray[indexPath.row];
//    cell.viewerModel = self.viewmodel.viewerModelArray[indexPath.row];
    return cell;
    
}


//返回itme的size
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake((WIDTH - 4)/4, (self.height - _bottomToolView.height) / 2 - 5);
}

//item的点击
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
        
     self.sendButton.userInteractionEnabled = YES;
    for (giftModel * model in self.giftViewModel.giftArray) {
            model.isSelected = @"0";
      }
        giftModel * selectModel = self.giftViewModel.giftArray[indexPath.row];
        selectModel.isSelected = @"1";
        [self.collectView reloadData];
        self.sendButton.backgroundColor = mainButtonColor;
        self.giftViewModel.selectGiftMdoel = selectModel;
    
}

-(giftModel *)bygiftModelWith:(NSString *)code
{
    giftModel *mdoel = [[[HMessageTool messgeTool] giftdict] objectForKey:code];
    return mdoel;
}


-(void)relaodData
{
    [self.collectView reloadData];
}
-(void)show
{
    KLCPopup *newpop = [KLCPopup popupWithContentView:self];
    newpop.showType = KLCPopupShowTypeSlideInFromBottom;
    newpop.dismissType = KLCPopupDismissTypeSlideOutToBottom;
    newpop.maskType = KLCPopupMaskTypeClear;
    self.pop = newpop;
    [newpop showAtCenter:CGPointMake(WIDTH/2.0, HEIGHT - self.frame.size.height/2) inView:[[UIApplication sharedApplication].delegate window]];
}

-(void)dismis
{
    [self.pop dismiss:YES];
}

-(void)topUp
{
    [self dismis];
    MTWalletViewController *walletVc =  [[MTWalletViewController alloc] init];
    [self.targetViewcontroller.navigationController pushViewController:walletVc animated:YES];
}

-(void)SendGiftClick:(UIButton *)sendbutton
{
    if(self.balanceViewModel.currentDiamondNumber > 0)
    {
       [self sendGiftResult];
    }else{
        [self showMoneyNotEnoughWarning];
    }
   
}

-(void)sendGiftResult
{
    if(![MTWalletApiManager manager].walletInfo.setPassword)
    {
        [self notBindPhoneWarning];
    }else
    {
        if(self.token == nil)
        {
            @weakify(self);
            [self.passwordView show];
            self.passwordView.passwordView.completeBlock = ^(NSString *password) {
                @strongify(self);
                [self sendGiftClickPassword:password token:nil];
            };
        }else
        {
            [self sendGiftClickPassword:nil token:self.token];
        }
        
    }
}

-(void)sendGiftClickPassword:(NSString *)password token:(NSString *)token
{
    
    [[MTLiveApiManager manager] sendGiftWithAnchorId:self.liveModel.anchor.userId
                                              giftId:self.giftViewModel.selectGiftMdoel.id
                                              liveId:self.liveModel.Id
                                            password:password token:token completion:^(NSString *token, MTError *error) {
                                                if(error == nil)
                                                {
                                                    NSLog(@"送礼成功");
                                                    self.sendButton.hidden = YES;
                                                    [self.passwordView dismis];
                                                    self.receivedCount = 50;
                                                    [self.giftCountDownTimer setFireDate:[NSDate distantPast]]; //开启定时
                                                    if (self.giftViewModel.selectGiftMdoel == self.lastGiftModel) {
                                                        [self.giftViewModel.selectGiftMdoel setnowtime];
                                                    }else{
                                                        self.giftViewModel.selectGiftMdoel.oldtime = 0;
                                                        [self.giftViewModel.selectGiftMdoel setnowtime];
                                                    }
                                                    self.lastGiftModel = self.giftViewModel.selectGiftMdoel;
                                                    self.balanceViewModel.currentDiamondNumber = self.balanceViewModel.currentDiamondNumber - self.giftViewModel.selectGiftMdoel.price;
                                                    self.diamondNumberLabel.text = [NSString stringWithFormat:@"%ld", self.balanceViewModel.currentDiamondNumber];
                                                    
                                                    self.token = token;
                                                    
                                                    LTMessage *message  = [LTSDKHelper sendGiftMessageWithGiftModel:self.giftViewModel.selectGiftMdoel roomId:self.liveModel.chatRoomId];
                                                    if(self.delegate && [self.delegate respondsToSelector:@selector(hliveSendGiftViewWithMesage:)])
                                                    {
                                                        [self.delegate hliveSendGiftViewWithMesage:message];
                                                    }
                                                }else if(error.code == 2){
                                                    [MBProgressHUD showMessage:@"密码错误或者密码输入时间过期，请重新输入密码。"];
                                                    @weakify(self);
                                                     [self.passwordView.passwordView clearPassword];
                                                    self.passwordView.passwordView.completeBlock = ^(NSString *password) {
                                                        @strongify(self);
                                                        [self sendGiftClickPassword:password token:nil];
                                                    };
                                                }else
                                                {
                                                    
                                                    [MBProgressHUD showMessage:error.errorDescription];
                                                    [self.passwordView.passwordView clearPassword];
                                                    [self.passwordView dismis];
                                                }
                                            }];
    
}


-(void)notBindPhoneWarning
{
    [[MTWalletApiManager manager] pushSetPasswordVcFromVc:self.targetViewcontroller];
}

-(void)showMoneyNotEnoughWarning
{
    UIAlertController *tipAddfriend = [UIAlertController alertControllerWithTitle:NSLTLocalizedString(@"提示", nil) message:NSLTLocalizedString(@"您的余额不足，请先充值", nil) preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:NSLTLocalizedString(@"充值", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            MTWalletViewController *diamondVC = [[MTWalletViewController alloc]init];
            [self.targetViewcontroller.navigationController pushViewController:diamondVC animated:YES];
        
    }];
    UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:NSLTLocalizedString(@"取消", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {

    }];
    [tipAddfriend addAction:cancleAction];
    [tipAddfriend addAction:sureAction];
    [self.targetViewcontroller presentViewController:tipAddfriend animated:YES completion:nil];
}

//送礼物
-(void)sendGifMessageWithgiftModel:(giftModel *)model
{

}

-(void)viewerMoneyRefresh
{

    
}
-(void)setViewerMoney:(NSInteger)viewerMoney
{
    NSLog(@"%ld",viewerMoney);
    _viewerMoney = viewerMoney;
    self.diamondNumberLabel.text = [NSString stringWithFormat:@"%ld",viewerMoney];
}

-(void)giftCountDownRefresh
{
    self.countTimeLabel.text = [NSString stringWithFormat:@"%ld", self.receivedCount];
    self.countDownButton.hidden = NO;
    if (self.receivedCount == 0) {
        [self.giftCountDownTimer setFireDate:[NSDate distantFuture]]; //暂停定时器
        self.sendButton.hidden = NO;
        self.countDownButton.hidden = YES;
    }
    self.receivedCount --;
}
-(void)sendGiftButtonPressed:(UIButton *)but
{
        //逻辑判断与发送礼物
    self.sendButton.hidden = YES;
    [self sendGiftResult];
}
-(void)clearTimer
{
    [self.giftCountDownTimer invalidate];
    self.giftCountDownTimer = nil;
    
    [self.giftRefrshTimer invalidate];
    self.giftCountDownTimer = nil;
    
}
-(void)refreshBalance
{
    self.diamondNumberLabel.text = [NSString stringWithFormat:@"%ld", self.balanceViewModel.currentDiamondNumber];
    
}
-(void)dealloc
{
    NSLog(@"dealloc --sendGiftModelArray");
    
}
@end
